# -*- coding: utf-8 -*-
import decimal
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10024': {
        'API_KEY': '0685b124de31db133f7590ccc17985c3b517320a',
        # 'gateway': 'https://pay.hyinpin.com/apisubmit',
        'gateway': 'http://www.hyinpay.com/apisubmit',
        'query_gateway': 'http://pay.hyinpay.com/apiorderquery',
    },
    '10022': {
        'API_KEY': 'a19ad46dbbef65fb7754b511e24dae07131bdf0f',
        # 'gateway': 'https://pay.hyinpin.com/apisubmit',
        'gateway': 'http://www.hyinpay.com/apisubmit',
        'query_gateway': 'http://pay.hyinpay.com/apiorderquery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def gen_order_sign(d, key):
    s = 'version={}&customerid={}&total_fee={}&sdorderno={}&notifyurl={}&returnurl={}&{}'.format(
        d['version'], d['customerid'], d['total_fee'], d['sdorderno'], d['notifyurl'], d['returnurl'], key
    )
    return generate_sign(s)


def gen_notify_sign(d, key):
    s = 'customerid={}&status={}&sdpayno={}&sdorderno={}&total_fee={}&paytype={}&{}'.format(
        d['customerid'], d['status'], d['sdpayno'], d['sdorderno'], d['total_fee'], d['paytype'], key
    )
    return generate_sign(s)


def gen_query_sign(d, key):
    s = 'customerid={}&sdorderno={}&reqtime={}&{}'.format(
        d['customerid'], d['sdorderno'], d['reqtime'], key
    )
    return generate_sign(s)


def verify_notify_sign(params, key):
    calculated_sign = gen_notify_sign(params, key)
    if params['sign'] != calculated_sign:
        _LOGGER.info("huiyintongpay sign: %s, calculated sign: %s", params['sign'], calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 微信H5	gzhpay
# 在线网银	bank
# 支付宝wap	alipaywap
# 快捷支付	quickbank
# QQ扫码	qqrcode
# QQH5	qqwallet
def _get_pay_type(service):
    if service == 'wxpay':
        pay_type = 'gzhpay'
    elif service == 'qq':
        pay_type = 'qqwallet'
    elif service == 'quickbank':
        pay_type = 'quickbank'
    elif service == 'alipay':
        pay_type = 'alipay'
    else:
        pay_type = 'qqwallet'
    return pay_type


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    _LOGGER.info('huiyintongpay app_id: %s, api_key: %s', app_id, api_key)
    p_dict = OrderedDict((
        ('version', '1.0'),
        ('customerid', app_id),
        ('sdorderno', str(pay.id)),
        ('total_fee', decimal.Decimal(pay_amount).quantize(decimal.Decimal('0.00'))),
        ('paytype', _get_pay_type(service)),
        ('notifyurl', '{}/pay/api/{}/huiyintongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('returnurl', '{}/pay/api/{}/huiyintongpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('remark', 'edcwsxqaz'),
    ))
    p_dict['sign'] = gen_order_sign(p_dict, api_key)
    _LOGGER.info('huiyintongpay before data: %s', p_dict)
    html = _build_form(p_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# response 'success'
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("huiyintongpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['sdorderno']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huiyintongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['sdpayno']
    total_fee = float(data['total_fee'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('huiyintongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)

    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    query_gateway = _get_query_gateway(app_id)
    p_dict = OrderedDict((
        ('customerid', app_id),
        ('sdorderno', pay_order.id),
        ('reqtime', time.strftime("%Y%m%d%H%M%S")),
    ))
    p_dict['sign'] = gen_query_sign(p_dict, api_key)
    response = requests.post(query_gateway, data=p_dict, timeout=3)
    _LOGGER.info('huiyintongpay query, %s', response.text)
    if response.status_code == 200:
        mch_id = pay_order.mch_id
        j = json.loads(response.text)
        trade_status = str(j['status'])
        total_fee = float(j['total_fee'])
        trade_no = pay_order.id

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee
        }

        if trade_status == '1' and total_fee > 0:
            _LOGGER.info('huiyintongpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
